
/*!
	\file
	\brief Resultant document.

		\author Igor Mironchik (igor.mironchik at gmail dot com).

        Copyright (c) 2010 - 2011 Igor Mironchik

	Permission is hereby granted, free of charge, to any person
	obtaining a copy of this software and associated documentation
	files (the "Software"), to deal in the Software without
	restriction, including without limitation the rights to use,
	copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the
	Software is furnished to do so, subject to the following
	conditions:

	The above copyright notice and this permission notice shall be
	included in all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
	EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
	OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
	NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
	HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
	WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
	FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
	OTHER DEALINGS IN THE SOFTWARE.
*/

// eShopHelper include.
#include <eShopHelper/h/document.hpp>

// Qt include.
#include <QtXml/QDomDocument>

#include <QtCore/QFile>
#include <QtCore/QTextStream>


namespace eShopHelper {

//
// DocumentException
//

DocumentException::DocumentException( const QString & what )
	:	std::runtime_error( what.toLocal8Bit().data() )
	,	m_what( what )
{
}

DocumentException::~DocumentException() throw()
{
}

const QString &
DocumentException::whatAsQString() const throw()
{
	return m_what;
}


//
// Document
//

Document::Document()
{
}

Document::~Document()
{
}

const Document::CorrepondenciesMap &
Document::correspondencies() const
{
	return m_correspondencies;
}

Document::CorrepondenciesMap &
Document::correspondencies()
{
	return m_correspondencies;
}

void
Document::correspondencies( const CorrepondenciesMap & map )
{
	m_correspondencies = map;
}

void
Document::addCorrespondence( const CorrepondenciesMap::key_type & excelFile,
	const CorrepondenciesMap::mapped_type & format )
{
	m_correspondencies.insert( excelFile, format );
}

void
Document::delCorrepondence( const CorrepondenciesMap::key_type & excelFile )
{
	m_correspondencies.remove( excelFile );
}

namespace /* anonymous */ {

static const QLatin1String documentTagName = QLatin1String( "document" );

static const QLatin1String correspondenciesTagName =
	QLatin1String( "correspondencies" );

static const QLatin1String correspondenceTagName =
	QLatin1String( "correspondence" );

static const QLatin1String fileTagName = QLatin1String( "file" );

static const QLatin1String formatTagName = QLatin1String( "format" );


} /* namespace anonymous */

void
Document::readFromFile( const QString & fileName )
{
	QMap< QString, QString > correspondencies;

	QFile file( fileName );

	if( file.open( QIODevice::ReadOnly ) )
	{
		QDomDocument doc;

		QString error;
		int errorLine = 0;

		if( !doc.setContent( &file, &error, &errorLine ) )
		{
			file.close();

			throw DocumentException( QLatin1String( "Unable to set XML content." ) +
				" Reason : \"" + error + "\". Error line: " +
				QString::number( errorLine ) );
		}

		QDomElement elem = doc.documentElement();

		if( elem.tagName() != documentTagName )
			throw DocumentException( QLatin1String( "Wrong document format." ) +
				" Tag \"" + documentTagName + "\" doesn't present." );

		QDomNode correspondenciesNode = elem.namedItem( correspondenciesTagName );

		if( correspondenciesNode.isNull() )
			throw DocumentException( QLatin1String( "Wrong document format." ) +
				" Tag \"" + correspondenciesTagName + "\" doesn't present." );

		QDomNode n = correspondenciesNode.firstChild();

		while( !n.isNull() )
		{
			QDomElement e = n.toElement();

			if( e.isNull() || e.tagName() != correspondenceTagName )
				throw DocumentException( QLatin1String( "Wrong document format." ) +
					" Unexpected tag occured. Tag name: \"" + e.tagName() + "\"." );

			QDomElement fileNode = n.namedItem( fileTagName ).toElement();
			QDomElement formatNode = n.namedItem( formatTagName ).toElement();

			if( fileNode.isNull() )
				throw DocumentException( QLatin1String( "Wrong document format." ) +
					" \"" + fileTagName + "\" doesn't present."  );

			if( formatNode.isNull() )
				throw DocumentException( QLatin1String( "Wrong document format." ) +
					" \"" + formatTagName + "\" doesn't present."  );

			correspondencies.insert( fileNode.text(), formatNode.text() );

			n = n.nextSibling();
		}
	}
	else
		throw DocumentException( QLatin1String( "Unable to open file: \"" ) +
			fileName + "\"" );

	file.close();

	m_correspondencies = correspondencies;
}

void
Document::saveIntoFile( const QString & fileName ) const
{
	QDomDocument doc;

	QDomElement root = doc.createElement( documentTagName );
	doc.appendChild( root );

	QDomElement correspondencies = doc.createElement( correspondenciesTagName );
	root.appendChild( correspondencies );

	QMapIterator< QString, QString > it( m_correspondencies );

	while( it.hasNext() )
	{
		it.next();

		QDomElement correspondence = doc.createElement( correspondenceTagName );
		correspondencies.appendChild( correspondence );

		QDomElement fileNode = doc.createElement( fileTagName );
		QDomText fileNodeText = doc.createTextNode( it.key() );
		fileNode.appendChild( fileNodeText );
		correspondence.appendChild( fileNode );

		QDomElement formatNode = doc.createElement( formatTagName );
		QDomText formatNodeText = doc.createTextNode( it.value() );
		formatNode.appendChild( formatNodeText );
		correspondence.appendChild( formatNode );
	}

	QFile file( fileName );
	file.open( QFile::WriteOnly | QFile::Truncate );

	if( file.isOpen() && file.isWritable() )
	{
		QTextStream stream( &file );

		doc.save( stream, 4 );

		file.close();
	}
	else
	{
		file.close();

		throw DocumentException(
			QLatin1String( "Unable to save document. Unable to open file: \"" ) +
				fileName + "\"." );
	}
}

} /* namespace eShopHelper */
